/*
 *
 *      Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the lxcloud.com developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: lengleng (wangiegie@gmail.com)
 *
 */

package com.example.common.log.aspect;

import com.example.common.i18n.util.SpringContextHolder;
import com.example.common.log.annotation.MemberLog;
import com.example.common.log.event.MemberLogEvent;
import com.example.common.log.util.MemberLogUtils;
import com.example.common.msg.dto.MemberLogDTO;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

/**
 * 操作日志使用spring event异步入库
 *
 * @author L.cm
 */
@Aspect
@Slf4j
public class MemberLogAspect {

	@Around("@annotation(memberLog)")
	public Object around(ProceedingJoinPoint point, MemberLog memberLog) throws Throwable {
		String strClassName = point.getTarget().getClass().getName();
		String strMethodName = point.getSignature().getName();
		log.debug("[类名]:{},[方法]:{}", strClassName, strMethodName);

		MemberLogDTO logDTO = MemberLogUtils.getLog();
		logDTO.setTitle(memberLog.value());
		// 发送异步日志事件
		Object obj = null;
		Long startTime = System.currentTimeMillis();
		try {
			obj = point.proceed();
			Long endTime = System.currentTimeMillis();
			logDTO.setTime(endTime - startTime);
		} catch (Throwable t) {
			Long endTime = System.currentTimeMillis();
			logDTO.setTime(endTime - startTime);
			logDTO.setException(t.getMessage());
			throw t;
		}finally {
			SpringContextHolder.publishEvent(new MemberLogEvent(logDTO));
		}
		return obj;
	}

}
